package com.meilingcloud.quartz.task;

import com.meilingcloud.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * 数据库备份
 */
@Slf4j
@Component("backupDatabaseTask")
public class BackupDatabaseTask {

    @Value("${spring.datasource.druid.master.url}")
    private String url;
    @Value("${spring.datasource.druid.master.username}")
    private String userName;
    @Value("${spring.datasource.druid.master.password}")
    private String password;

    @Value("${bims.backupPath}")
    private String backupPath;

    /**
     * 获取数据库名
     */
    public String getDataBaseName() {
        return url.substring(url.indexOf("3306"), url.indexOf("?")).replaceAll("/", "").replaceAll("3306", "");
    }

    /**
     * 获取主机地址
     */
    private String getHost() {
        return url.substring(url.indexOf("mysql"), url.indexOf("3306")).replace(":", "").replace("//", "").replace("mysql", "");
    }

    public void run() {
        String curDate = DateUtils.getDate();
        // 指定导出的 sql 存放的文件夹
        File saveFile = new File(backupPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        String host = getHost();
        String dataBaseName = getDataBaseName();
        String fileName = curDate + "_" + "bims.sql";

        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --result-file=").append(backupPath + fileName).append(" --default-character-set=utf8 ").append(dataBaseName);

        try {
            Process exec = Runtime.getRuntime().exec(sb.toString());
            if (exec.waitFor() == 0) {
                log.info("数据库备份成功，保存路径：" + backupPath);
            } else {
                System.out.println("process.waitFor()=" + exec.waitFor());
            }
        } catch (IOException e) {
            log.error("备份 数据库 出现 IO异常 ", e);
        } catch (InterruptedException e) {
            log.error("备份 数据库 出现 线程中断异常 ", e);
        } catch (Exception e) {
            log.error("备份 数据库 出现 其他异常 ", e);
        }
    }

}
